package com.emm.yixun.system.service.impl.manage;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.mapper.SubscribeMapper;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.TransactionRelation;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.MsgUtil;

@Service("customerNoSignedNoticeManage")
public class CustomerNoSignedNoticeManage {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private SubscribeMapper subscribeMapper;
	@Autowired
	private TransactionRelationService transactionRelationService;

	/**
	 * 插入消息【逾期未签约】
	 * 
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice() {
		CommonResDTO resDto = new CommonResDTO();
		resDto.setResult("0");
		try {
			// 获取逾期未签约数据
			List<Subscribe> subscribeList = subscribeMapper.selectEntityList();
			if (subscribeList != null) {
				// 逾期未签约提醒模板 NT01
				String sendTemp = "客户${customer}已经逾期${day}天未签约，请尽快处理或申请延期签约。";

				// 消息内容模板
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDictionaryValue("NT01");
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if (dic != null)
					sendTemp = dic.getDictionaryName();

				// 遍历逾期未签约客户信息
				for (Subscribe subscribe : subscribeList) {
					// 组装推送消息
					Customer customer = customerService.selectById(subscribe.getCustomerId());
					if (null == customer)
						continue;
					try {
						// 逾期天数=当日日期-认购转签约日
						Long day = DateUtils.getDaysSub(subscribe.getConversionSignDate(), new Date());
						String sendMsg = sendTemp.replace("${customer}", customer.getCustomerName()).replace("${day}",
								day.toString());
						Map<String, String> noticeParamMap = new HashMap<String, String>();
						noticeParamMap.put("noticeDicId", "160");
						noticeParamMap.put("noticeTempType", "NT01");
						noticeParamMap.put("sendMsg", sendMsg);
						noticeParamMap.put("title", "逾期未签约提醒");
						noticeParamMap.put("merchantId", String.valueOf(subscribe.getMerchantId()));
						noticeParamMap.put("projectCode", subscribe.getProjectCode());
						noticeParamMap.put("userCode", subscribe.getUserCode());
						noticeParamMap.put("accessCode", subscribe.getAccessCode());
						noticeParamMap.put("createUserId", String.valueOf(subscribe.getCreateUserId()));
						noticeParamMap.put("tempType", "4");

						/*
						 * (ym) 提醒内容增加超链接 start
						 */
						Map<String, String> replaceValuesMap = new HashMap<String, String>();
						replaceValuesMap.put(MsgUtil.ROOM_ID, "");
						replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
						replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
						replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
						replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
						replaceValuesMap.put(MsgUtil.BUSINESS_ID, String.valueOf(subscribe.getId()));
						noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
						/*
						 * (ym) 提醒内容增加超链接 end
						 */
						
						//判断是否已有消息
				    	CommonResDTO common = sysNoticeManage.isRepeated(noticeParamMap);
				    	if("1".equals(common.getResult())){
				    		continue;
				    	}

						// 经纪人
						List<User> userList = new ArrayList<User>();
						TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
						transactionRelationDto.setBusinessId(subscribe.getId());
						transactionRelationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
						List<TransactionRelation> transactionRelationList = transactionRelationService
								.selectListByDto(transactionRelationDto);
						if (transactionRelationList.size() > 0) {
							for (int i = 0; i < transactionRelationList.size(); i++) {
								User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
								if (user != null) {
									userList.add(user);
								}
							}
						}

						// 归属人
						if (StringUtils.isNotBlank(customer.getUserCode())) {
							UserDto userDto = new UserDto();
							userDto.setUserCode(customer.getUserCode());
							User user = userService.selectByDto(userDto);
							userList.add(user);
						}

						// 查询营销负责人、案场负责人、销管负责人
						ProjectSettingDto entity_proSetting = new ProjectSettingDto();
						entity_proSetting.setProjectCode(subscribe.getProjectCode());
						ProjectSetting projectSetting = projectSettingService.selectByDto(entity_proSetting);
						User user_sale, user_field, user_male = null;
						if (projectSetting != null) {
							// if (projectSetting.getSaleLeader() != null) {
							// user_sale = userService.selectById(projectSetting.getSaleLeader());// 营销负责人
							// userList.add(user_sale);
							// }
							if (projectSetting.getFieldLeader() != null) {
								user_field = userService.selectById(projectSetting.getFieldLeader());// 销售经理
								userList.add(user_field);
							}
							if (projectSetting.getMaLeader() != null) {
								user_male = userService.selectById(projectSetting.getMaLeader());// 销管负责人
								userList.add(user_male);
							}
						}

						// 去重
						Set<User> set = new HashSet<User>(userList);
						userList.clear();
						userList.addAll(set);

						sysNoticeManage.createNoticeWithNoticeTemp(noticeParamMap, userList);
					} catch (Exception e) {
						logger.error("createNotice error: ", e);
					}
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("添加逾期未签约提醒消息失败: ", e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加逾期未签约提醒消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

}
